class UsersController < ApplicationController

	load_and_authorize_resource except: [:show, :create]

	before_action :set_user, only: [:show, :edit, :update, :destroy]

	def index
		@users = initialize_grid(User.includes(:creator),:order=>"updated_at")
	end

	def show

	end

	def new
		# sign_out("user")
		# redirect_to new_user_registration_path
	end

	def edit

	end

	def create_new
		@user = User.new(user_params.merge(:creator_id=>current_user.id))
	    respond_to do |format|
	      if @user.save
	      	 create_note(:target_id=>@user.id,:target_name=>@user.name)
	        format.html { redirect_to users_path, notice: 'User was successfully created.' }
	        format.json { render :show, status: :created, location: @user }
	      else
	        format.html { render :new }
	        format.json { render json: @user.errors, status: :unprocessable_entity }
	      end
	    end
	end

	
	def update
		respond_to do |format|
	      if @user.update(user_params)
	      	create_note(:target_id=>@user.id,:target_name=>@user.name)
	        format.html { redirect_to users_path, notice: 'User was successfully updated.' }
	        format.json { render :show, status: :ok, location: @user }
	      else
	        format.html { render :edit }
	        format.json { render json: @user.errors, status: :unprocessable_entity }
	      end
	    end
	end

	def destroy
		if @user.id == current_user.id
			notice = '不能删除当前用户'
		elsif @user.is_sys_admin || @user.is_master
			notice = '不能删除系统管理员'
		else 
			@user.destroy 
			create_note(:target_id=>@user.id,:target_name=>@user.name)
		end
	    respond_to do |format|
	      format.html { redirect_to users_url, notice: notice }
	      format.json { head :no_content }
	    end
	end

	private 

	def set_user
		@user = User.find(params[:id])
	end

	def user_params
      params.require(:user).permit(:email,:name,:is_sys_admin,:enabled,:phone,:password,:password_confirmation)
    end

end